package com.syt.mina.handler;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.mina.core.session.IoSession;
import org.springframework.context.support.ApplicationObjectSupport;

import com.syt.mina.handler.service.HandlerInterceptor;
import com.syt.mina.handler.service.HandlerMapping;


public abstract class AbstractHandlerMapping extends ApplicationObjectSupport implements HandlerMapping {
	private final List<Object> interceptors = new ArrayList<Object>();
	private Object defaultHandler;
	private HandlerInterceptor[] adaptedInterceptors;
	
	public void setInterceptors(Object[] interceptors) {
		this.interceptors.addAll(Arrays.asList(interceptors));
	}
	
	
	public final HandlerExecutionChain getHandler(IoSession session, Object message)throws Exception{
		Object handler = getHandlerInternal(session, message);
		if (handler == null) {
			handler = getDefaultHandler();
		}
		if (handler == null) {
			return null;
		}
		// Bean name or resolved handler?
		if (handler instanceof String) {
			String handlerName = (String) handler;
			handler = getApplicationContext().getBean(handlerName);
		}
		return getHandlerExecutionChain(handler, session, message);
	}
	
	protected HandlerExecutionChain getHandlerExecutionChain(Object handler, IoSession session, Object message) {
		if (handler instanceof HandlerExecutionChain) {
			HandlerExecutionChain chain = (HandlerExecutionChain) handler;
			chain.addInterceptors(getAdaptedInterceptors());
			return chain;
		}
		else {
			return new HandlerExecutionChain(handler, getAdaptedInterceptors());
		}
	}

	protected abstract Object getHandlerInternal(IoSession session, Object message) throws Exception;
	
	public Object getDefaultHandler() {
		return defaultHandler;
	}


	public void setDefaultHandler(Object defaultHandler) {
		this.defaultHandler = defaultHandler;
	}
	
	protected final HandlerInterceptor[] getAdaptedInterceptors() {
		return this.adaptedInterceptors;
	}
	
}
